package com.chris.security.jwt;

import com.chris.repository.UserRepository;
import com.chris.security.utils.LoginUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component("jwtUserService")
public class JwtUserService implements UserDetailsService {

    private Logger log = LoggerFactory.getLogger(getClass());

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return getUserDetails(username);
    }

    public UserDetails getUserDetails(String username) {
        com.chris.domain.User byUsername = userRepository.findByUsername(username);
        String encode = new BCryptPasswordEncoder().encode("111");
        return new User(username, encode, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,user"));
//        return new User(username,
//                new BCryptPasswordEncoder().encode("111"),
//                true,
//                true,
//                true,
//                true,
//                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,user"));
    }

    public String saveUserLoginInfo(UserDetails user) {
        com.chris.domain.User byUsername = userRepository.findByUsername("chris");
        return LoginUtils.getToken("1", user.getUsername());
    }

    public void createUser(String username, String password) {
        String encryptPwd = passwordEncoder.encode(password);
        /**
         * @todo 保存用户名和加密后密码到数据库
         */
    }

    public void deleteUserLoginInfo(String username) {
        /**
         * @todo 清除数据库或者缓存中登录salt
         */
    }
    
}
